using System;
using System.Linq;
using System.Collections.Generic;
using Microsoft.EntityFrameworkCore;
using Abp.Domain.Repositories;
using Abp.Domain.Entities.Auditing;
using System.ComponentModel;
using System.Threading.Tasks;

namespace Yozeev.BusinessLogic.DomainService
{
	/// <summary>
	/// Device领域层的业务管理
	///</summary>
	public class DeviceManager :YozeevDomainServiceBase, IDeviceManager
    {
		
		private readonly IRepository<Device,Guid> _repository;

		private readonly IRepository<VerifiableSet, Guid> _verifiableRepository;

		/// <summary>
		/// Device的构造方法
		///</summary>
		public DeviceManager(
			IRepository<Device, Guid> repository
			, IRepository<VerifiableSet, Guid> verifiableRepository
		)
		{
			_repository =  repository;
			_verifiableRepository = verifiableRepository;
		}


		/// <summary>
		/// 初始化
		///</summary>
		public void InitDevice()
		{
			throw new NotImplementedException();
		}

		public Tuple<Device,List<VerifiableTypeEnum>> GetDeviceByCode(string deviceCode)
		{
			var query = from device in _repository.GetAll().AsNoTracking()
						.Where(m => m.DeviceCode == deviceCode)
						select new
						{
							device,
							list = (from ts in _verifiableRepository.GetAll().AsNoTracking().Where(m => m.DeviceId == device.Id)
									select ts.VerifiableType).ToList(),
						};
			return Tuple.Create(query.FirstOrDefault().device, query.FirstOrDefault().list);
		}

		/// <summary>
		/// 根据设备编号查询设备支持证件类型
		/// </summary>
		/// <param name="deviceCode">设备编号</param>
		/// <returns></returns>
		public IQueryable<IdentityInfo> GetIdentitiesAsync(string deviceCode)
		{
			var query = _verifiableRepository.GetAll()
				.Where(v => v.Device.DeviceCode.Equals(deviceCode));
			return query.Select(v => new IdentityInfo
			{
				IdentityType = v.VerifiableType,
				IdentityName = ((DescriptionAttribute)(typeof(VerifiableTypeEnum).GetMember(v.VerifiableType.ToString())[0]
				.GetCustomAttributes(typeof(DescriptionAttribute), false)[0])).Description
			});
		}
	}
}
